package api

import (
	"github.com/gin-gonic/gin"
	"seat-service/model/dto"
	"seat-service/response"
	service "seat-service/service/impl"
	"strconv"
	"time"
)

var reservationService service.ReservationService

type ReservationApi struct {
}

func (*ReservationApi) QueryReservation(c *gin.Context) {
	page := c.Query("page")
	pageSize := c.Query("page_size")
	p, _ := strconv.Atoi(page)
	ps, _ := strconv.Atoi(pageSize)
	reservation, err := reservationService.QueryReservation(p, ps)
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, reservation)

}

func (*ReservationApi) QueryConditionReservation(c *gin.Context) {
	page := c.Query("page")
	pageSize := c.Query("page_size")
	p, _ := strconv.Atoi(page)
	ps, _ := strconv.Atoi(pageSize)

	name := c.Query("name")
	studentNumber := c.Query("student_number")
	building := c.Query("building")
	classroom := c.Query("classroom")
	seat := c.Query("seat")
	reserveStatus := c.Query("reserve_status")
	appointmentTimeStart := c.Query("appointment_time_start")
	appointmentTimeEnd := c.Query("appointment_time_end")

	if name == "" {
		name = "%"
	}
	if studentNumber == "" {
		studentNumber = "%"
	}
	if building == "" {
		building = "%"
	}
	if classroom == "" {
		classroom = "%"
	}
	if seat == "" {
		seat = "%"
	}

	if reserveStatus == "" {
		reserveStatus = "%"
	}
	if appointmentTimeStart == "" {
		appointmentTimeStart = "0000000000"
	}
	if appointmentTimeEnd == "" {
		appointmentTimeEnd = "9999999999"
	}
	startUnix, _ := strconv.ParseInt(appointmentTimeStart, 10, 64)
	endUnix, _ := strconv.ParseInt(appointmentTimeEnd, 10, 64)
	start := time.Unix(startUnix, 0)
	end := time.Unix(endUnix, 0)
	reservation, err := reservationService.QueryConditionReservation(p, ps, name, studentNumber, building, classroom, seat, reserveStatus, start, end)
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, reservation)
}

func (*ReservationApi) CancelReservation(c *gin.Context) {
	var crd dto.CancelReservationDto
	err := c.ShouldBindJSON(&crd)
	if err != nil {
		response.Fail(c, response.DataInWrongFormat, nil)
		return
	}
	numId, _ := strconv.Atoi(crd.Id)
	err = reservationService.CancelReservation(uint(numId))
	if err != nil {
		response.Fail(c, response.DatabaseException, nil)
		return
	}
	response.Success(c, response.CodeSuccess, nil)

}
